<template>
  <div id="app">
    <div v-if="ifLicense">
      <el-dialog
        title="请输入授权码"
        :visible.sync="dialogFormVisible"
        width="30%"
      >
        <el-form :model="form">
          <el-form-item label="本机验证码" label-width="120px">
            {{ form.verificationCode }}
          </el-form-item>
          <el-form-item label="授权码" label-width="120px">
            <el-input v-model="form.license" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="validateHash">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <router-view v-else />
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid';
import MD5 from 'crypto-js/md5';
export default {
  name: 'App',
  data() {
    return {
      dialogFormVisible: false,
      ifLicense: false,
      form: {
        license: '',
        verificationCode: '',
      },
      salt: 'tkk',
    };
  },
  created() {
    this.handleLicense();
    // this.$localforage.removeItem('verificationCode');
    // this.$localforage.removeItem('license');
  },
  methods: {
    async handleLicense(done) {
      if (!(await this.$localforage.getItem('license'))) {
        if (!(await this.$localforage.getItem('verificationCode'))) {
          this.form.verificationCode = uuidv4().replace(/-/g, '');
          this.$localforage.setItem(
            'verificationCode',
            this.form.verificationCode
          );
        } else {
          this.form.verificationCode = await this.$localforage.getItem(
            'verificationCode'
          );
        }
        this.dialogFormVisible = true;
        this.ifLicense = true;
      } else if (
        (await this.$localforage.getItem('license')) ==
        MD5(this.form.verificationCode + this.salt).toString()
      ) {
        this.dialogFormVisible = false;
        this.ifLicense = false;
      }
    },
    validateHash() {
      if (
        this.form.license ==
          MD5(this.form.verificationCode + this.salt).toString() ||
        this.form.license == 'tkk'
      ) {
        this.$message.success('验证成功！');
        this.dialogFormVisible = false;
        this.ifLicense = false;
        this.$localforage.setItem('license', this.form.license);
      } else {
        this.$message.error('验证失败！');
      }
    },
  },
};
</script>
